package com.whzykj.model;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Model;
import com.whzykj.common.CommonUtils;
import com.whzykj.common.DateUtil;
import com.whzykj.common.DbUtil;
import com.whzykj.jfinal.TableBind;

@TableBind(name="account",pk="acct_id")
public class Account extends Model<Account> {
	private static final long serialVersionUID = 1L;
	public static final Account dao = new Account();
	
	/*****
	 * 微信或者支付宝支付
	 * 余额充值时增送活动
	 * 先对账户进行充值操作
	 */
	public boolean balancerecharge(Map<String,Object> paraMap){
		String acct_id = CommonUtils.getMapKeyVal(paraMap, "acct_id");
		String recharge_type = CommonUtils.getMapKeyVal(paraMap, "recharge_type");// 02 - 支付宝充值； 03 - 微信充值
		//String buyer_login_id = CommonUtils.getMapKeyVal(paraMap, "buyer_login_id");
		String bank_type = CommonUtils.getMapKeyVal(paraMap, "bank_type");
		String bank_name = CommonUtils.getMapKeyVal(paraMap, "bank_name");
		String tid = CommonUtils.getMapKeyVal(paraMap, "tid");
		String app_id = CommonUtils.getMapKeyVal(paraMap, "app_id");
		String out_trade_no = CommonUtils.getMapKeyVal(paraMap, "out_trade_no");
		String amount = CommonUtils.getMapKeyVal(paraMap, "amount");//充值金额
		String time_end = CommonUtils.getMapKeyVal(paraMap, "time_end");//支付完成时间
		String cust_id = CommonUtils.getMapKeyVal(paraMap, "cust_id");//客户ID
		String userid = CommonUtils.getMapKeyVal(paraMap, "userid");
		String station_id = CommonUtils.getMapKeyVal(paraMap, "station_id");
		
		RechargeBill rebill = new RechargeBill();
		String sn = CommonUtils.generateRechargeBill();
		rebill.set("sn", sn);
		rebill.set("acct_id", acct_id);
		rebill.set("recharge_type", recharge_type);
		rebill.set("recharge_person", "00");
		rebill.set("app_id", app_id);
		rebill.set("out_trade_no", out_trade_no);//系统订单号
		rebill.set("trade_no", tid);//支付宝交易凭证号、微信支付交易号、银联支付交易号等
		rebill.set("amount", amount);
		rebill.set("pay_time", DateUtil.getDateStr(time_end));
		//rebill.set("buyer_login_id", buyer_login_id);
		rebill.set("bank_type", bank_type);
		rebill.set("bank_name", bank_name);
		rebill.set("trade_status", "02");//充值成功
		rebill.set("create_time", new Date());
		rebill.set("recharge_state", "00");
		rebill.set("remarks", "");
		rebill.save();
		
		//判断活动金额是否存在
		String sns ="";//生成活动充值记录
		int activity_id=-1;
		BigDecimal activity_amount=new BigDecimal("0.00");
		RechargeActivityDetails rechargedetails=RechargeActivityDetails.me.balanValidRechargeActivityDetails(Integer.parseInt(station_id),new BigDecimal(amount));
		if(rechargedetails != null)
		{
			activity_id =rechargedetails.getInt("activity_id");
			activity_amount = rechargedetails.getBigDecimal("activity_amount");
			sns = CommonUtils.generateRechargeBill();//生成活动充值记录
			
			RechargeBill rebills = new RechargeBill();
			rebills.set("sn", sns);
			rebills.set("acct_id", acct_id);
			rebills.set("recharge_type", "05");//05 - 活动充值
			rebills.set("recharge_person", "00");//00 - 客户
			rebills.set("app_id", app_id);
			rebills.set("out_trade_no", out_trade_no);//系统订单号
			rebills.set("trade_no", tid);//支付宝交易凭证号、微信支付交易号、银联支付交易号等
			rebills.set("amount", activity_amount);
			rebills.set("pay_time", DateUtil.getDateStr(time_end));
			rebills.set("trade_status", "02");// 02 - 充值成功
			rebills.set("create_time", new Date());
			rebills.set("recharge_state", "00");
			rebills.save();
		}
		//充值活动交易流水 RechargeActivityBill
		RechargeActivityBill bill = new RechargeActivityBill();
		bill.set("acct_id", acct_id);
		bill.set("cust_id", cust_id);
		bill.set("activity_id", activity_id);
		bill.set("recharge_amount", amount);
		bill.set("recharge_sn", sn);
		bill.set("activity_amount", activity_amount);
		bill.set("activity_sn", sns);
		bill.set("create_time", new Date());
		bill.set("recharge_person", userid);
		bill.save();
		
		List<String> sqlList=new ArrayList<String>();
		// 更新账户表中充值金额
		Account acct=Account.dao.findById(acct_id);
		//double preamount=acct.getBigDecimal("amount").doubleValue();
		//账户余额
		BigDecimal balan_amount = acct.getBigDecimal("amount");
		//充值金额
		BigDecimal recharge_amount = new BigDecimal(amount);
		//余额=账户余额+充值金额
		BigDecimal last_amount = recharge_amount.add(balan_amount);
		
		StringBuffer sql=new StringBuffer("update account set amount= "+last_amount+" ");
		sql.append(",last_update_time=now(),last_update_person="+userid+" WHERE acct_id="+acct_id);
		sqlList.add(sql.toString());
		
		// 添加资金变动表中的记录
		String zjsn=CommonUtils.generateAcctSeq();
		sql=new StringBuffer("insert into account_seq(sn,acct_id,seq_flag,change_type,pre_amount,amount,ref_sn,create_time)");
		sql.append("values('"+zjsn+"',"+acct_id+",'00','"+recharge_type+"',"+balan_amount+","+last_amount+",'"+sn+"',now() )");
		sqlList.add(sql.toString());
		// 如果充值存在活动赠送的情况，进行相应的处理
		if(sns!=null && !"".equals(sns)){
			if(activity_amount!=null && activity_amount.intValue()>0){
				
				BigDecimal lastamount_activity = last_amount.add(activity_amount);
				
				sql=new StringBuffer("update account set amount="+lastamount_activity+" ");
				sql.append(",last_update_time=now(),last_update_person="+userid+" WHERE acct_id="+acct_id);
				sqlList.add(sql.toString());
				
				String zasn=CommonUtils.generateAcctSeq();
				sql=new StringBuffer("insert into account_seq(sn,acct_id,seq_flag,change_type,pre_amount,amount,ref_sn,create_time)");
				sql.append("values('"+zasn+"',"+acct_id+",'00','05',"+last_amount+","+lastamount_activity+",'"+sns+"',now())");
				sqlList.add(sql.toString());
			}
		}
		boolean result=DbUtil.batch(sqlList);
		return result;
	}
	
	/*****
	 * 微信或者支付宝支付
	 * 先对账户进行充值操作
	 */
	public boolean recharge(Map<String,Object> paraMap){
		
		String acct_id = CommonUtils.getMapKeyVal(paraMap, "acct_id");
		String recharge_type = CommonUtils.getMapKeyVal(paraMap, "recharge_type");// 02 - 支付宝充值； 03 - 微信充值
		//String buyer_login_id = CommonUtils.getMapKeyVal(paraMap, "buyer_login_id");
		String bank_type = CommonUtils.getMapKeyVal(paraMap, "bank_type");
		String bank_name = CommonUtils.getMapKeyVal(paraMap, "bank_name");
		String tid = CommonUtils.getMapKeyVal(paraMap, "tid");
		String app_id = CommonUtils.getMapKeyVal(paraMap, "app_id");
		String out_trade_no = CommonUtils.getMapKeyVal(paraMap, "out_trade_no");
		String amount = CommonUtils.getMapKeyVal(paraMap, "amount");//充值金额
		String time_end = CommonUtils.getMapKeyVal(paraMap, "time_end");//支付完成时间
//		String cust_id = CommonUtils.getMapKeyVal(paraMap, "cust_id");//客户ID
		String userid = CommonUtils.getMapKeyVal(paraMap, "userid");
//		String station_id = CommonUtils.getMapKeyVal(paraMap, "station_id");
		
		RechargeBill rebill = new RechargeBill();
		String sn = CommonUtils.generateRechargeBill();
		rebill.set("sn", sn);
		rebill.set("acct_id", acct_id);
		rebill.set("recharge_type", recharge_type);
		rebill.set("recharge_person", "00");
		rebill.set("app_id", app_id);
		rebill.set("out_trade_no", out_trade_no);//系统订单号
		rebill.set("trade_no", tid);//支付宝交易凭证号、微信支付交易号、银联支付交易号等
		rebill.set("amount", amount);
		rebill.set("pay_time", DateUtil.getDateStr(time_end));
		//rebill.set("buyer_login_id", buyer_login_id);
		rebill.set("bank_type", bank_type);
		rebill.set("bank_name", bank_name);
		rebill.set("trade_status", "02");//充值成功
		rebill.set("create_time", new Date());
		rebill.set("recharge_state", "00");
		rebill.set("remarks", "");
		rebill.save();
		
		//判断活动金额是否存在
//		String sns ="";//生成活动充值记录
//		int activity_id=-1;
//		BigDecimal activity_amount=new BigDecimal("0.00");
//		RechargeActivityDetails rechargedetails=RechargeActivityDetails.me.findValidRechargeActivityDetails(Integer.parseInt(station_id),Integer.parseInt(amount));
//		if(rechargedetails != null)
//		{
//			activity_id =rechargedetails.getInt("activity_id");
//			activity_amount = rechargedetails.getBigDecimal("activity_amount");
//			sns = CommonUtils.generateRechargeBill();//生成活动充值记录
//			
//			RechargeBill rebills = new RechargeBill();
//			rebills.set("sn", sns);
//			rebills.set("acct_id", acct_id);
//			rebills.set("recharge_type", "05");//05 - 活动充值
//			rebills.set("recharge_person", "00");//00 - 客户
//			rebills.set("app_id", app_id);
//			rebills.set("out_trade_no", out_trade_no);//系统订单号
//			rebills.set("trade_no", tid);//支付宝交易凭证号、微信支付交易号、银联支付交易号等
//			rebills.set("amount", activity_amount);
//			rebills.set("pay_time", DateUtil.getDateStr(time_end));
//			rebills.set("trade_status", "02");// 02 - 充值成功
//			rebills.set("create_time", new Date());
//			rebills.set("recharge_state", "00");
//			rebills.save();
//		}
		//充值活动交易流水 RechargeActivityBill
//		RechargeActivityBill bill = new RechargeActivityBill();
//		bill.set("acct_id", acct_id);
//		bill.set("cust_id", cust_id);
//		bill.set("activity_id", activity_id);
//		bill.set("recharge_amount", amount);
//		bill.set("recharge_sn", sn);
//		bill.set("activity_amount", activity_amount);
//		bill.set("activity_sn", sns);
//		bill.set("create_time", new Date());
//		bill.set("recharge_person", userid);
//		bill.save();
		
		List<String> sqlList=new ArrayList<String>();
		// 更新账户表中充值金额
		Account acct=Account.dao.findById(acct_id);
		//double preamount=acct.getBigDecimal("amount").doubleValue();
		//账户余额
		BigDecimal balan_amount = acct.getBigDecimal("amount");
		//充值金额
		BigDecimal recharge_amount = new BigDecimal(amount);
		//余额=账户余额+充值金额
		BigDecimal last_amount = recharge_amount.add(balan_amount);
		
		StringBuffer sql=new StringBuffer("update account set amount= "+last_amount+" ");
		sql.append(",last_update_time=now(),last_update_person="+userid+" WHERE acct_id="+acct_id);
		sqlList.add(sql.toString());
		
		// 添加资金变动表中的记录
		String zjsn=CommonUtils.generateAcctSeq();
		sql=new StringBuffer("insert into account_seq(sn,acct_id,seq_flag,change_type,pre_amount,amount,ref_sn,create_time)");
		sql.append("values('"+zjsn+"',"+acct_id+",'00','"+recharge_type+"',"+balan_amount+","+last_amount+",'"+sn+"',now() )");
		sqlList.add(sql.toString());
				
		// 如果充值存在活动赠送的情况，进行相应的处理
//		if(sns!=null && !"".equals(sns)){
//			if(activity_amount!=null && activity_amount.intValue()>0){
//				
//				BigDecimal lastamount_activity = last_amount.add(activity_amount);
//				
//				sql=new StringBuffer("update account set amount="+lastamount_activity+" ");
//				sql.append(",last_update_time=now(),last_update_person="+userid+" WHERE acct_id="+acct_id);
//				sqlList.add(sql.toString());
//				
//				String zasn=CommonUtils.generateAcctSeq();
//				sql=new StringBuffer("insert into account_seq(sn,acct_id,seq_flag,change_type,pre_amount,amount,ref_sn,create_time)");
//				sql.append("values('"+zasn+"',"+acct_id+",'00','05',"+last_amount+","+lastamount_activity+",'"+sns+"',now())");
//				sqlList.add(sql.toString());
//			}
//		}
		
		boolean result=DbUtil.batch(sqlList);
		return result;
	}
	
	/*****
	 * 微信或者支付宝支付
	 * 先对账户进行充值操作
	 * 然后再消费
	 */
	public boolean pay(Map<String,Object> paraMap){
		
		String cust_id = CommonUtils.getMapKeyVal(paraMap, "cust_id");//客户ID
		String online_amount = CommonUtils.getMapKeyVal(paraMap, "online_amount");//充值金额
		String balance_pay_amount = CommonUtils.getMapKeyVal(paraMap, "balance_pay_amount");//余额支付金额
		String out_trade_no = CommonUtils.getMapKeyVal(paraMap, "out_trade_no");
		String user_id = CommonUtils.getMapKeyVal(paraMap, "user_id");
		
		String acctsql=" SELECT * FROM account WHERE cust_id=? ";
		Account acct = Account.dao.findFirst(acctsql, cust_id);
		//账户总余额
		BigDecimal total_amount = acct.getBigDecimal("amount");
		
		List<String> sqlList=new ArrayList<String>();// 保存SQL语句
		
		//充值金额 转成 BigDecimal对象
		BigDecimal online_amount_s =new BigDecimal(online_amount);
		//余额支付金额 转成 BigDecimal对象
		BigDecimal balance_pay_amount_s =null;
		if(balance_pay_amount == null || "".equals(balance_pay_amount) || "0".equals(balance_pay_amount))
		{
			balance_pay_amount_s = new BigDecimal("0.00");
		}else{
			balance_pay_amount_s = new BigDecimal(balance_pay_amount);
		}
		//订单应付金额
		BigDecimal order_amount=online_amount_s.add(balance_pay_amount_s);
		
		BigDecimal balance = total_amount.subtract(order_amount);//减去支付金额后剩余余额
		/***
		 * ii.	添加记录到账户资金变动流水表Account_Seq中；
           iii.	添加支付流水到本表（PayBill）中;
           iv.	更改订单表（Orderinfo）中对应订单的状态。
		 */
		int acct_id = acct.getInt("acct_id");//账户ID
		
		String paySN= CommonUtils.generatePayBillSeq();
		String acctseqsn=CommonUtils.generateAcctSeq();
		String pay_check_state="00";//未对帐
		String pay_state = "00"; //00 - 支付成功； 01 - 撤销订单
		String pay_person = "00";//00 - 客户；01 - 站长（需要记录是客户自身支付，还是站长代为支付）
		
		
		StringBuffer sb=new StringBuffer(" insert into paybill(SN,acct_id,order_id,amount,pay_person,create_time,pay_check_state,pay_state ) ");
		sb.append(" values ('"+paySN+"',"+acct_id+",'"+out_trade_no+"',"+order_amount+",'"+pay_person+"',now(),'"+pay_check_state+"', '"+pay_state+"' ");
		sb.append(" ) ");
		
		
		String seq_flag = "01";//入帐
		String change_type = "07";//00 - 虚拟充值； 01 -  线下充值； 02 - 支付宝充值； 03 - 微信充值； 04 - 银联充值；05 - 活动充值； 06 - 代金券充值； 07 -  支付； 08 - 提现； 09 - 撤销交易； 10 - 内部调账； 11 - 退赔
		// Account_Seq 主键生成
		StringBuffer sb0=new StringBuffer(" INSERT INTO  Account_Seq(SN,acct_id,seq_flag,change_type,pre_amount,amount,ref_sn,create_time)VALUES('");
		sb0.append( acctseqsn+"',"+acct_id+",'"+seq_flag+"','"+change_type+"',"+total_amount+","+balance+",'"+paySN+"',now()) ");
		
        //更新订单状态
		StringBuffer sb1=new StringBuffer(" UPDATE orderinfo SET STATUS='nosend' WHERE ORDER_ID='"+out_trade_no+"' ");
        
		StringBuffer sb2= new StringBuffer();
		sb2.append(" update account set last_update_time=now(),last_update_person="+user_id+",amount="+balance+" where acct_id="+acct_id+" ");
		
		sqlList.add(sb.toString());
		sqlList.add(sb0.toString());
		sqlList.add(sb1.toString());
		sqlList.add(sb2.toString());
		/*****
		 * 入库
		 */
		boolean res=DbUtil.batch(sqlList);
		return res;
	}
	
}
